package models;

import java.util.*;

import javax.persistence.*;

import models.Event.Category;
 
import play.db.jpa.*;

@Entity
public class User extends Model {
	
	public enum ProfileTypes{
		NormalUser, PrivilgedUser, Administrator
	}
	
	@OneToMany(mappedBy="author", cascade=CascadeType.ALL)
	public List<Event> ownEvents;
	
	@ManyToMany(mappedBy="registeredUsers", cascade=CascadeType.ALL)
	public List<Event> registeredEvents;
	
	@ManyToMany
	public List<Event> invitations;

	public String firstName;
	public String lastName;
	public String email;
	public String userName;
	public String password;
	public String gender;
	public Date dateOfBirth;
	public String phoneNumber;
	public String town;
	public ProfileTypes profileType;
	
	public User(String firstName, String lastName, String email,
			String userName, String password, String gender, Date dateOfBirth,
			String phoneNumber, String town) {
		super();
		this.firstName = firstName;
		this.lastName = lastName;
		this.email = email;
		this.userName = userName;
		this.password = password;
		this.gender = gender;
		this.dateOfBirth = dateOfBirth;
		this.phoneNumber = phoneNumber;
		this.town = town;
		this.profileType = ProfileTypes.NormalUser;
	}
	public void updateProfile(ProfileTypes profile)
	{
		this.profileType = profile;
	}
	public static User connect(String email, String password) {
	    return find("byEmailAndPassword", email, password).first();
	}
	
	public Event addEvent(String title, String description, Category category, Date date, String location) {
		Event newEvent = new Event(this, title, description, category, date, location).save();
		this.ownEvents.add(newEvent);
		this.save();
		return newEvent;
	}
	
	public void registerToEvent(Event event) {
		registeredEvents.add(event);
		if(invitations.contains(event)) {
			invitations.remove(event);
		}
		this.save();
		event.registerUser(this);
	}
	
	public void unregisterToEvent(Event event) {
		registeredEvents.remove(event);
		this.save();
		event.unregisterUser(this);
	}
	
	public void addInvitation(Event event) {
		if((!invitations.contains(event)) && (!registeredEvents.contains(event))) {
			invitations.add(event);
			this.save();
		}
	}
	
	public void removeInvitation(Event event) {
		if(invitations.contains(event)) {
			invitations.remove(event);
			this.save();
		}
	}
}


